<?php
App::uses('AppController', 'Controller');
/**
 * Reviews Controller
 *
 * @property Review $Review
 */
class ReviewsController extends AppController {
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('home', 'ultimos_reviews', 'ler');
	}


	public function index() {
		$this->Review->recursive = 0;
		$this->set('reviews', $this->paginate());
	}


	public function add() {
		if ($this->request->is('post')) {
			$this->Review->create();
			if ($this->Review->save($this->request->data)) {
				$this->Session->setFlash(__('The review has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The review could not be saved. Please, try again.'));
			}
		}
		// TODO Fazer um sistema decente para os nomes 
		$produtos = $this->Review->Produto->find('list');
		$usuarios = $this->Review->Usuario->find('list');
		$this->set(compact('produtos', 'usuarios'));
	}


	public function edit($id = null) {
		$this->Review->id = $id;
		if (!$this->Review->exists()) {
			throw new NotFoundException(__('Invalid review'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Review->save($this->request->data)) {
				$this->Session->setFlash(__('The review has been saved'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The review could not be saved. Please, try again.'));
			}
		} else {
			$this->request->data = $this->Review->read(null, $id);
		}
		$produtos = $this->Review->Produto->find('list');
		$usuarios = $this->Review->Usuario->find('list');
		$this->set(compact('produtos', 'usuarios'));
	}


	public function delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Review->id = $id;
		if (!$this->Review->exists()) {
			throw new NotFoundException(__('Invalid review'));
		}
		if ($this->Review->delete()) {
			$this->Session->setFlash(__('Review deleted'));
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Review was not deleted'));
		$this->redirect(array('action' => 'index'));
	}
	
	
	public function home(){
		$this->css_array[] = "home";
		$this->ultimos_reviews();
	}
	
	/**
	 * @param $tipo = 'tudo' ou 'teste'
	 * @param unknown_type $usuario
	 */
	public function ultimos_reviews($tipo = 'tudo', $usuario = null){
		return $this->Review->ultimosReviews($tipo, $usuario);
	}
	
	public function meus_reviews($tipo = 'tudo'){
		$dados = $this->Review->reviewsPorUsuario($tipo, $this->usuarioLogado['id']);
		$this->set('dados', $dados);
	}
	
	public function ler($id = null, $recursive = 0){
		if(is_null($id))
			throw new NotFoundException("Review inválido");
		$this->Review->recursive = $recursive;
		$result = $this->Review->findById($id);
		if(empty($result))
			throw new NotFoundException("Review inválido");
		$this->set('dados', $result);
	}
}
